package com.zsqat.eshop.ware.service.impl;

import com.zsqat.common.constant.WareConstant;
import com.zsqat.eshop.ware.entity.PurchaseDetailEntity;
import com.zsqat.eshop.ware.service.PurchaseDetailService;
import com.zsqat.eshop.ware.service.WareSkuService;
import com.zsqat.eshop.ware.vo.MergeVo;
import com.zsqat.eshop.ware.vo.PurchaseDoneVo;
import com.zsqat.eshop.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsqat.common.utils.PageUtils;
import com.zsqat.common.utils.Query;
import com.zsqat.eshop.ware.dao.PurchaseDao;
import com.zsqat.eshop.ware.entity.PurchaseEntity;
import com.zsqat.eshop.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
  @Autowired
  private PurchaseDetailService purchaseDetailService;

  @Autowired
  private WareSkuService wareSkuService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<PurchaseEntity> page = this.page(
        new Query<PurchaseEntity>().getPage(params),
        new QueryWrapper<PurchaseEntity>()
    );

    return new PageUtils(page);
  }

  // 未领取采购订单，以便合并订单时查找
  @Override
  public PageUtils queryPageUnreceive(Map<String, Object> params) {
    QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<PurchaseEntity>()
        .eq("status", 0).or().eq("status", 1);

    IPage<PurchaseEntity> page = this.page(
        new Query<PurchaseEntity>().getPage(params),
        wrapper
    );

    return new PageUtils(page);
  }

  // 合并订单
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void mergePurchase(MergeVo mergeVo) {
    Long purchaseId = mergeVo.getPurchaseId();

    // 没有选择任何【采购单】，将自动创建新单进行合并。
    if (purchaseId == null) {
      PurchaseEntity purchaseEntity = new PurchaseEntity();
      //设置采购单的默认状态
      purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());

      purchaseEntity.setCreateTime(new Date());
      purchaseEntity.setUpdateTime(new Date());
      this.save(purchaseEntity);

      // 获取新建采购单的id
      purchaseId = purchaseEntity.getId();

    }

    List<Long> items = mergeVo.getItems();

    // TODO 确认采购单状态是0,1才可以合并
    Collection<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(items);

    purchaseDetailEntities.forEach((item) -> {
      if (!item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
          && !item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())) {
        throw new IllegalArgumentException("正在采购，无法进行分配");
      }
    });

    Long finalPurchaseId = purchaseId;
    List<PurchaseDetailEntity> collect = items.stream().map(i -> {
      PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
      purchaseDetailEntity.setId(i);
      purchaseDetailEntity.setPurchaseId(finalPurchaseId);
      purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
      return purchaseDetailEntity;
    }).collect(Collectors.toList());

    // 批量修改
    purchaseDetailService.updateBatchById(collect);

    PurchaseEntity purchaseEntity = new PurchaseEntity();
    purchaseEntity.setId(purchaseId);
    purchaseEntity.setUpdateTime(new Date());
    this.updateById(purchaseEntity);
  }

  // 领取采购单(采购人员通过手机领取属于自己名下的采购单)
  @Override
  public void received(List<Long> ids) {
    //1、确认当前采购单是新建或者是已分配状态
    List<PurchaseEntity> collect = ids.stream().map(id -> {
      PurchaseEntity byId = this.getById(id);
      return byId;
    }).filter(item -> {
      if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
          item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
        return true;
      }
      return false;
    }).map(item -> {
      //改变完状态的采购单
      item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
      item.setUpdateTime(new Date());
      return item;
    }).collect(Collectors.toList());

    //2、改变采购单的状态
    this.updateBatchById(collect);

    //3、改变采购项的状态
    collect.forEach((item) -> {
      List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPurchaseId(item.getId());
      List<PurchaseDetailEntity> detailEntities = list.stream().map(entity -> {

        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
        purchaseDetailEntity.setId(entity.getId());
        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
        return purchaseDetailEntity;
      }).collect(Collectors.toList());
      purchaseDetailService.updateBatchById(detailEntities);
    });
  }

  // 完成采购单(采购人员通过手机完成属于自己名下的采购单，没完成的需要写没完成原因)
  @Override
  public void done(PurchaseDoneVo doneVo) {
    Long id = doneVo.getId();

    //1、改变采购项的状态
    Boolean flag = true;
    List<PurchaseItemDoneVo> items = doneVo.getItems();
    List<PurchaseDetailEntity> updates = new ArrayList<>();

    for (PurchaseItemDoneVo item : items) {
      PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
      if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
        flag = false;
        purchaseDetailEntity.setStatus(item.getStatus());
      } else {
        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
        //3、将成功采购的进行入库
        //查出当前采购项的详细信息
        //PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
        PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
        wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

      }
      purchaseDetailEntity.setId(item.getItemId());

      updates.add(purchaseDetailEntity);
    }

    //批量更新
    purchaseDetailService.updateBatchById(updates);

    //2、改变采购单状态
    PurchaseEntity purchaseEntity = new PurchaseEntity();
    purchaseEntity.setId(id);
    purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
    purchaseEntity.setUpdateTime(new Date());
    this.updateById(purchaseEntity);
  }

}